package com.huwaiwai.nio.demo04;

import java.io.IOException;
import java.nio.channels.SelectionKey;
import java.nio.channels.Selector;
import java.nio.channels.ServerSocketChannel;
import java.util.Iterator;
import java.util.Set;

/**
 * Selector（选择器）是Java NIO中能够检测一到多个NIO通道，并能够知晓通道是否为诸如读写事件做好准备的组件。
 * 这样，一个单独的线程可以管理多个channel，从而管理多个网络连接
 * Created by huweiwei on 2017/4/20.
 */
public class MySelector {

    public static void main(String [] args) throws IOException {
        ServerSocketChannel socketChannel = ServerSocketChannel.open();
        //创建
        Selector selector = Selector.open();
        socketChannel.configureBlocking(true);
        SelectionKey key = socketChannel.register(selector, SelectionKey.OP_READ);
        while (true) {
            int readyChannels = selector.select();
            if (readyChannels == 0) {
                continue;
            }
            Set<SelectionKey> selectedKeys = selector.selectedKeys();
            Iterator<SelectionKey> keyIterator = selectedKeys.iterator();
            while (keyIterator.hasNext()) {
                SelectionKey s = keyIterator.next();
                if (s.isAcceptable()) {

                } else if (s.isConnectable()) {

                } else if (s.isReadable()) {

                } else if (s.isWritable()) {

                }
                keyIterator.remove();
            }
        }


    }
}
